package com.api.workflow.web;

import com.api.workflow.util.YNHttpUtils;
import com.weaver.general.BaseBean;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.TimeUtil;
import weaver.interfaces.schedule.BaseCronJob;

import java.util.*;

/*
 * 接口22   PMI001 设备台账查询接口 定时任务
 * */
public class YNNPMI001Task extends BaseCronJob {
    public static void main(String[] args) {

    }

    /**
     * 定时从接口拿数据   zyzcbh重复就更新/不重复就新增
     */
    @Override
    public void execute() {
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog("==================YNNPMI001Task=============");
        try {
            RecordSet recordSet = new RecordSet();
            RecordSet recordSet1 = new RecordSet();
            RecordSet recordSet2 = new RecordSet();

            //公司代码表
            String gsSelects = "select bm from uf_gsdmb";
            String GcSelects = "select bh from uf_gcb where gsdm = ?";
            String ufSbxx = "select * from uf_sbxx where gsdm = ? and sbh = ?";
            int hrmResourceId = getModeId("uf_sbxx");
            recordSet.execute(gsSelects);

            while (recordSet.next()) {
                String bm = recordSet.getString("bm");
                recordSet1.executeQuery(GcSelects, bm);
                Map<String, Object> insetMap = new HashMap<>();
                while (recordSet1.next()) {
                    String bh = recordSet1.getString("bh");
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("BUKRS", bm);
                    jsonObject.put("WERKS", bh);
                    baseBean.writeLog("==============jsonObject===:"+jsonObject.toString());
                    String post = YNHttpUtils.PMI001(jsonObject.toString(), YNHttpUtils.token());
                    baseBean.writeLog("==============post===:"+post);
                    JSONObject jsonPost = JSONObject.parseObject(post);
                    String STATUS = jsonPost.getString("STATUS");
                    if ("S".equals(STATUS)) {
                        JSONArray data = jsonPost.getJSONArray("DATA");
                        for (int i = 0; i < data.size(); i++) {
                            JSONObject jsonObject1 = data.getJSONObject(i);
                            insetMap.put("gsdm", jsonObject1.getString("BUKRS"));
                            insetMap.put("gsdmhgsmc", jsonObject1.getString("BUTXT"));
                            insetMap.put("gc", jsonObject1.getString("WERKS"));
                            insetMap.put("mc", jsonObject1.getString("NAME1"));
                            insetMap.put("zyzcbh", jsonObject1.getString("ANLN1"));
                            insetMap.put("zcms", jsonObject1.getString("TXT50"));
                            insetMap.put("sbh", jsonObject1.getString("EQUNR"));
                            insetMap.put("jsdxms", jsonObject1.getString("EQKTX"));
                            insetMap.put("gnwz", jsonObject1.getString("TPLNR"));
                            insetMap.put("gnwzms", jsonObject1.getString("PLTXT"));
                            insetMap.put("cbzx", jsonObject1.getString("KOSTL"));
                            insetMap.put("ms", jsonObject1.getString("LTEXT"));
                            insetMap.put("bmbm", jsonObject1.getString("ZSYBMNO"));
                            insetMap.put("bmms", jsonObject1.getString("ZSYBMMS"));
                            insetMap.put("ryxm", jsonObject1.getString("ZSYR"));
                            insetMap.put("gzzx", jsonObject1.getString("ARBPL"));
                            insetMap.put("dms", jsonObject1.getString("KTEXT"));
                            insetMap.put("fj", jsonObject1.getString("MSGRP"));
                            insetMap.put("zcyz", jsonObject1.getString("ZASSETYZ"));
                            insetMap.put("zcjz", jsonObject1.getString("ZASSETJZ"));
                            insetMap.put("zzsxh", jsonObject1.getString("TYPBZ"));
                            insetMap.put("mc1", jsonObject1.getString("NAME"));
                            insetMap.put("gjdqdm", jsonObject1.getString("COUNTRY"));
                            insetMap.put("whrwdgzzx", jsonObject1.getString("GEWRK"));
                            insetMap.put("zzsxlh", jsonObject1.getString("SERGE"));
                            insetMap.put("syrygh", jsonObject1.getString("ZSYRNO"));
                            String wybs = jsonObject1.getString("BUKRS")+ jsonObject1.getString("EQUNR");
                            insetMap.put("wybs",wybs);//唯一标识

                            recordSet2.executeQuery(ufSbxx, jsonObject1.getString("BUKRS"), jsonObject1.getString("EQUNR"));
                            Map<String, Object> whereMap = new HashMap<>();
                            whereMap.put("gsdm", jsonObject1.getString("BUKRS"));
                            whereMap.put("sbh", jsonObject1.getString("EQUNR"));
                            recordSet2.next();
                            int counts = recordSet2.getCounts();
                            if (counts == 0) {
                                boolean b = insetModeData("uf_sbxx", insetMap, 1, hrmResourceId);
                                baseBean.writeLog("==============新增===:"+b);
                            } else {
                                boolean b = updateModeData("uf_sbxx", insetMap, whereMap);
                                baseBean.writeLog("==============修改===:"+b);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            baseBean.writeLog("=========YNNPMI001Task========error:"+e.getMessage());
        }

    }

    public static boolean updateModeData(String tableName, Map<String, Object> data, Map<String, Object> updateData) throws Exception {
        String columns = "";
        String updateColumns = "";
        // 处理 SET 部分
        for (Map.Entry<String, Object> stringObjectEntry : data.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            if (value == null) {
                columns += key + " = NULL, ";
            } else if (value instanceof String) {
                String strValue = (String) value;
                if (strValue.isEmpty()) {
                    columns += key + " = '', ";
                } else {
                    String escaped = strValue.replace("'", "''");
                    columns += key + " = '" + escaped + "', ";
                }
            } else {
                columns += key + " = " + value + ", ";
            }
        }

        // 处理 WHERE 条件
        for (Map.Entry<String, Object> stringObjectEntry : updateData.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            if (value == null) {
                updateColumns += key + " = NULL AND ";
            } else if (value instanceof String) {
                String strValue = (String) value;
                if (strValue.isEmpty()) {
                    updateColumns += key + " = '' AND ";
                } else {
                    String escaped = strValue.replace("'", "''");
                    updateColumns += key + " = '" + escaped + "' AND ";
                }
            } else {
                updateColumns += key + " = " + value + " AND ";
            }
        }

        String insertSql = "update  " + tableName + " set " + columns;
        if (insertSql.endsWith(", ")) {
            insertSql = insertSql.substring(0, insertSql.length() - 2);
        }
        insertSql = insertSql + " where ";
        if (updateColumns.endsWith("AND ")) {
            updateColumns = updateColumns.substring(0, updateColumns.length() - 4);
        }
        insertSql = insertSql + updateColumns;
        RecordSet updateRs = new RecordSet();
        return updateRs.executeUpdate(insertSql);
    }


    /**
     * 插入到建模表数据
     *
     * @param tableName
     * @param data
     * @param hrmResourceId
     * @param modeId
     * @return
     * @throws Exception
     */
    public static boolean insetModeData(String tableName, Map<String, Object> data, int hrmResourceId, int modeId) throws Exception {
        List<Object> dataList = new ArrayList<>();
        String columns = "";
        String values = "";
        for (Map.Entry<String, Object> stringObjectEntry : data.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            columns += (key + ",");
            values += ("?,");
            dataList.add(value);
        }

        String insertSql = "insert into  " + tableName + "(" +
                columns +
                " formmodeid," +
                " modedatacreater," +
                " modedatacreatertype," +
                " modedatacreatedate," +
                " modedatacreatetime, " +
                " MODEUUID" +
                ") values(" +
                values +
                "?,?,?,?,?,?)";
        String currentDateString = TimeUtil.getCurrentDateString();
        String currentTimeString = TimeUtil.getOnlyCurrentTimeString();
        String uuid = UUID.randomUUID().toString();

        Object[] objects = new Object[]{
                modeId, hrmResourceId, 0, currentDateString, currentTimeString, uuid
        };
        dataList.addAll(Arrays.asList(objects));

        RecordSet insertRs = new RecordSet();
        boolean b1 = insertRs.executeUpdate(insertSql, dataList.toArray());
        if (b1) {
            RecordSet recordSet1 = new RecordSet();
            recordSet1.executeQuery("select max(id) as billid from " + tableName + " ");
            if (recordSet1.next()) {
                int billid = recordSet1.getInt("billid");
                ModeRightInfo ModeRightInfo = new ModeRightInfo();
                ModeRightInfo.setNewRight(true);
                ModeRightInfo.editModeDataShare(1, modeId, billid);
            }
        }
        return b1;
    }


    /**
     * @param tablename
     * @return
     */
    public static int getModeId(String tablename) {
        RecordSet rs = new RecordSet();
        Map<String, Integer> map = new HashMap<>();
        rs.executeQuery("select b.tablename,a.formid,b.detailkeyfield,a.id from modeinfo a,workflow_bill b where a.formid = b.id  and tablename=?", tablename);
        if (rs.next()) {
            int id = rs.getInt("id");
            return id;
        }
        return 0;
    }
}
